from django import template
from google.appengine.api import memcache
import re
import time
register = template.Library()

@register.filter
def filter_media(value):
    return value[:3]

@register.filter
def filter_thumbnails(value):
    return value[:1]

@register.filter
def summary(value):
    services = {
        'dailymotion': {
            'favorite': 'favorites',
        },
        'digg': {
            'comment': 'comments',
        },
        'facebook': {
            'note': 'notes',
            'post': 'posts',
        },
        'flickr': {
            'favorite': 'favorites',
        },
        'hatena': {
            'bookmark': 'bookmarks',
            'photo': 'photos',
            'post': 'posts',
        },
        'meneame': {
            'comment': 'comments',
        },
        'netflix': {
            'queue': 'queue',
            'instant': 'instant queue',
        },
        'netvibes': 'starred',
        'pandora': {
            'artist': 'artist',
        },
        'reddit': {
            'comment': 'comments',
        },
        'vimeo': {
            'like': 'favorites',
        },
        'wakoopa': {
            'review': 'reviews',
        },
        'youtube': {
            'favorite': 'favorites',
        },
        'zooomr': {
            'favorite': 'favorites',
        },
    }
    service = value['service']
    if service['id'] == 'internal':
        return ''
    entryType = service.get('entryType', None)
    type = services.get(service['id'], {}).get(entryType)
    if type:
        return ' '.join([service['name'], type])
    return service['name']

@register.filter
def gmpize(value, arg=None):
    if arg:
        if not 'f.huhaitai.com' in value:
            value = 'http://www.google.com/gwt/n?u=%s' % value
        return value
    from BeautifulSoup import BeautifulSoup
    soup = BeautifulSoup(value)
    for a in soup.findAll('a'):
        if not 'f.huhaitai.com' in a['href']:
            a['href'] = 'http://www.google.com/gwt/n?u=%s' % a['href']
    return soup

@register.filter
def is_admin(value, arg):
    return value in [administrator['nickname'] for administrator in arg['administrators']]

@register.filter
def is_message(value):
    services = (
        'googletalk',
        'identica',
        'plurk',
        'twitter',
    )
    if value['service']['id'] in services:
        return True
    if value['service']['id'] == 'jaiku':
        return value['service']['profileUrl'].lower() in value['link'].lower()
    if value['service']['id'] == 'facebook':
        return value['service'].get('entryType', None) != 'post'
    if value['service']['id'] == 'feed':
        return value['service'].get('entryType', None) != 'post'
    return value['link'] == 'http://friendfeed.com/e/%s' % value['id']

@register.filter
def likeable(value, arg):
    if value['anonymous']:
        return True
    return value['user']['nickname'] != arg

@register.filter
def liked(value, arg):
    return value in [like['user']['nickname'] for like in arg['likes']]

@register.filter
def shorten_comments(value, arg):
    if len(value) > 3 and len(arg) > 1:
        return value[:1] + [{'permalink': True, 'num': len(value) - 2},] + value[-1:]
    return value

@register.filter
def set_shorten_comments(value, arg):
    if len(value) > int(arg) >= 2:
        middle_c = len(value) - int(arg)
        last_c = int(arg) - 1
        return value[:1] + [{'permalink': True, 'num': middle_c},] + value[-last_c:]
    return value

@register.filter
def shorten_likes(value, arg):
    if len(value) > 4 and len(arg) > 1:
        return value[:3] + [{'permalink': True, 'num': len(value) - 3},]
    return value

@register.filter
def twitterize(value):
    import re
    for user in re.findall(r'@(\w+)', value):
        value = value.replace('@%s' % user, '@<a href="http://twitter.com/%s">%s</a>' % (user, user))
    return value

@register.filter
def iconproxy(value):
    #friendfeed services icon
    value = value.replace('http://friendfeed.com', '')
    return value

@register.filter
def unescape(value):
    "Returns the given HTML with ampersands, quotes and carets decoded"
    if not isinstance(value, basestring):
        value = str(value)
    return value.replace('&amp;', '&').replace('&lt;', '<').replace('&gt;', '>').replace('&quot;', '"').replace('&#39;',"'")

@register.filter
def content_link_url(content):
    regex_url = r'http:\/\/([\w.]+\/?)\S*'
    regex_user = '@([a-z_A-Z0-9]+)'
    regex_hash = '#([\w+]{1,139})'
    for match in re.finditer(regex_url, content):
        url = match.group(0)
        content = content.replace(url,'<a href="%s">%s</a>' %(url,url))
    for match in re.finditer(regex_user, content):
        user = match.group(0)
        content = content.replace(user,'@<a href="https://twitter.com/%s">%s</a>' %(user[1:],user[1:]))
    for match in re.finditer(regex_hash, content):
        hash = match.group(0)
        hs = '%23'
        content = content.replace(hash,'<a href="/search?query=%s%s">%s</a>' %(hs,hash[1:],hash))

    return content

@register.filter
def trendshash(content):
    regex_hash = '#([\w+]{1,139})'
    for match in re.finditer(regex_hash, content):
        hash = match.group(0)
        hs = '%23'
        content = content.replace(hash,'%s%s' %(hs,hash[1:]))

    return content

@register.filter
def create_time(create_at):
    try:
        b = time.strptime(create_at, '%a %b %d %H:%M:%S +0000 %Y')
        seconds = time.mktime(time.strptime(create_at, '%a %b %d %H:%M:%S +0000 %Y'))
    except:
        b = time.strptime(create_at, '%a, %d %b %Y %H:%M:%S +0000')
        seconds = time.mktime(time.strptime(create_at, '%a, %d %b %Y %H:%M:%S +0000'))
    fudge = 1.25
    delta  = int(time.mktime(time.gmtime())) - int(seconds)
    if delta < (1 * fudge):
        return 'about a second ago'
    elif delta < (60 * (1/fudge)):
        return 'about %d seconds ago' % (delta)
    elif delta < (60 * fudge):
        return 'about a minute ago'
    elif delta < (60 * 60 * (1/fudge)):
        return 'about %d minutes ago' % (delta / 60)
    elif delta < (60 * 60 * fudge):
        return 'about an hour ago'
    elif delta < (60 * 60 * 24 * (1/fudge)):
        return 'about %d hours ago' % (delta / (60 * 60))
    else:
        return time.strftime('%H:%M %p %b %d %Y', b)
